var scene, camera, renderer;
var controls;
var allTexture;
var ASSETSURL = "../assets/02/"; // 资源主目录路径
var mixer = null;
var clock = new THREE.Clock();
var animations = [];
var role = null;
var actionState = ""

// 初始化
function init() {
  scene = new THREE.Scene();
  createCamera();

  renderer = new THREE.WebGLRenderer({
    antialias: true,
  });
  renderer.setSize(document.body.clientWidth, document.body.clientHeight);
  renderer.setClearColor(new THREE.Color(0xaabbcc));
  renderer.shadowMap.enabled = true;
  document.getElementById("container").appendChild(renderer.domElement);

  controls = new THREE.OrbitControls(camera, renderer.domElement);

  loadAllTexture(function () {
    loadModel();
  });

  addLight();
  //createStage();
  loop();
}

// 创建相机
function createCamera() {
  camera = new THREE.PerspectiveCamera(
    90,
    document.body.clientWidth / document.body.clientHeight,
    0.2,
    1000
  );
  camera.position.set(-.2, 0.7, -0.75);
}

// 创建地面
function createStage() {
  var plane_map = new THREE.TextureLoader().load(ASSETSURL + "imgs/grass.jpg");
  plane_map.wrapS = THREE.RepeatWrapping;
  plane_map.wrapT = THREE.RepeatWrapping;
  plane_map.repeat.set(10,10);
  // MeshPhysicalMaterial
  // MeshBasicMaterial
  // MeshDepthMaterial
  // MeshLambertMaterial
  // MeshMatcapMaterial
  var mesh = new THREE.MeshPhysicalMaterial({
    map: plane_map,
    side: THREE.DoubleSide,
  });
  mesh.reflectivity = 0;
  mesh.clearCoatRoughness = .8;
  
  // mesh.roughness = 1;
  // mesh.metalness = 0.7;
  // mesh.reflectivity = 0;
  // mesh.emissiveIntensity = 0.1;
  // mesh.lightMapIntensity = 0.1;
  // mesh.skinning = true;
  // mesh.aoMapIntensity = 0;
  
  var plane = new THREE.Mesh(new THREE.BoxBufferGeometry(5, 5, 0.2), mesh);
  plane.receiveShadow = true;
  plane.position.set(0, -0.1, 0);
  plane.rotation.x = 0.5 * Math.PI;

  scene.add(plane);
}

// 批量加载所需纹理集
function loadAllTexture(cb) {
  allTexture = {};
  var loadIndex = 0;
  var textures = [
    {
      key: "claws_diffuse",
      format: ".png",
    },
    {
      key: "eyes_diffuse",
      format: ".jpeg",
    },
    {
      key: "fur__fella3_jpg_001_diffuse",
      format: ".png",
    },
    {
      key: "fur__fella3_jpg_001_occlusion",
      format: ".png",
    },
    {
      key: "fur__fella3_jpg_001_specularGlossiness",
      format: ".png",
    },
    {
      key: "Material__wolf_col_tga_diffuse",
      format: ".jpeg",
    },
    {
      key: "Material__wolf_col_tga_occlusion",
      format: ".png",
    },
    {
      key: "Material__wolf_col_tga_specularGlossiness",
      format: ".png",
    },
  ];
  function loadNextTexture() {
    var textureObj = textures[loadIndex];
    loadTexture(
      ASSETSURL + "textures/" + textureObj.key + textureObj.format,
      function (texture) {
        allTexture[textureObj.key] = {
          texture: texture,
        };
        if (loadIndex < textures.length - 1) {
          loadIndex++;
          loadNextTexture();
        } else {
          if (cb) cb();
        }
      }
    );
  }
  loadNextTexture();
}

// 加载纹理
function loadTexture(filepath, cb) {
  var textureLoader = new THREE.TextureLoader();
  textureLoader.load(filepath, cb);
}

// 加载模型
function loadModel(cb) {
  var loader = new THREE.GLTFLoader();
  loader.load(ASSETSURL + "scene.gltf", function (gltf) {
    var mesh = gltf.scene;
    mesh.children[0].position.set(0, 0.348112553358078, 0);
    // console.log(mesh.scale.set(100,100,100));
      
    role = mesh.children[0].children[0].children[0].children[0].children[0].children[0].children[0];
    role.direction = 0;
    role.rotation.y = role.direction
    // role.position.set(0,0,-2)
    // mixer.clipAction(gltf.animations[0]).play();
    
    mixer = new THREE.AnimationMixer(mesh);
    animations = gltf.animations;
    createAnimationUI(animations);
    actionAnimation(3);
    document.querySelectorAll("li")[3].className ="active";
   
    // console.log(gltf.animations);
    // mixer.clipAction(gltf.animations[0]).play();
    addMesh(mesh);
    addShadow(mesh);
    // console.log("-----Animation-----");
    scene.add(mesh);
    cb && cb();
  });
}

function actionAnimation(index) {
  actionState = animations[index].name;
  mixer.clipAction(animations[index]).play();
}

function createAnimationUI(animations) {
  var ul = document.createElement("ul");
  animations.forEach(function (ani, index) {
    var li = document.createElement("li");
    li.innerHTML = ani.name;
    li.addEventListener(
      "click",
      function (item) {
        var target = item.target;
        clearAction();
        if (target.className != "active") {
          target.className = "active";
          actionAnimation(index);
        } else {
          target.className = "";
        }
      },
      false
    );
    ul.appendChild(li);
  });
  document.body.appendChild(ul);
}

function clearAction() {
  mixer.stopAllAction();
  var ul = document.querySelectorAll("ul")[0];
  ul.childNodes.forEach(function (node) {
    node.className = "";
  });
}

function addMesh(obj) {
  if (!obj.children) return;
  for (var i = 0; i < obj.children.length; i++) {
    var item = obj.children[i];
    if (item.name == "Plane") {
      //item.children[0].material.color = new THREE.Color("rgb(255,0,0)");
      
      // console.log(item.position);
      //item.clear();
    }
    if(item.material){

      // item.material.emissive = new THREE.Color(0x000000);
      // item.material.color = new THREE.Color(0xffffff);
      // item.material.roughness = 0;
      // item.material.wireframe = true;
    }
    if (item.name == "Wolf3_eyes_0") {
      // console.log(item.name);
      // item.material = new THREE.MeshStandardMaterial();
      item.material.color = new THREE.Color("rgb(158,158,158)");
      item.material.emissive = new THREE.Color("rgb(102,102,102)");

      // item.material.map = allTexture["eyes_diffuse"].texture;
      // item.material.emissiveMap = allTexture["eyes_diffuse"].texture;
    }
    if (item.name == "Wolf3_claws_0") {
      // item.material = new THREE.MeshStandardMaterial();
      // item.material.map = allTexture["claws_diffuse"].texture;
    }
    if (item.name == "Wolf3_teeth__nor2_tga_0") {
    }
    if (item.name == "Wolf2_fur__fella3_jpg_001_0") {
      // item.material = new THREE.MeshStandardMaterial();
      item.material.color = new THREE.Color("rgb(158,158,158)");
      // item.material.map =
      //   allTexture["fur__fella3_jpg_001_diffuse"].texture;
      //   item.material.transparent = true;
      // item.material.normalMap =
      //   allTexture["fur__fella3_jpg_001_specularGlossiness"].texture;
      // item.material.aoMap = allTexture["fur__fella3_jpg_001_occlusion"].texture;
    }
    if (item.name == "Wolf1_Material__wolf_col_tga_0") {
      // console.log(item.material);
      // item.material = new THREE.MeshStandardMaterial();
      item.material.color = new THREE.Color("rgb(97,97,97)");
      // item.material.map = allTexture["Material__wolf_col_tga_diffuse"].texture;

      // item.material.aoMap =
      //   allTexture["Material__wolf_col_tga_occlusion"].texture;

      // item.material.normalMap =
      //   allTexture["Material__wolf_col_tga_specularGlossiness"].texture;
      // console.log(item.material);
    }

    addMesh(item);
  }
}

function addShadow(obj) {
  for (var i = 0; i < obj.children.length; i++) {
    var item = obj.children[i];
    item.castShadow = true;
    item.receiveShadow = true;
    if (item.children) {
      addShadow(item);
    }
  }
}

// 添加灯光
function addLight() {
  var ambientLight = new THREE.AmbientLight(0x000000);
  ambientLight.intensity = 2;
  scene.add(ambientLight);

  // var spotLight = new THREE.SpotLight(0xffffcc, 5);
  // spotLight.position.set(-10, 20, 5);
  // spotLight.castShadow = true;
  // spotLight.shadow.mapSize.width = 2048;
  // spotLight.shadow.mapSize.height = 2048;
  // scene.add(spotLight);

  // var helper = new THREE.SpotLightHelper(spotLight, 1);
  // scene.add(helper);

  var frontDirLight = new THREE.DirectionalLight(0xffffff);

  frontDirLight.position.x = -1;
  frontDirLight.position.y = 5;
  frontDirLight.position.z = -2;
  frontDirLight.intensity = 60;
  frontDirLight.castShadow = true;
  frontDirLight.receiveShadow = true;
  scene.add(frontDirLight);

  // var helper = new THREE.DirectionalLightHelper(frontDirLight, 1);
  // scene.add(helper);
  
}

// 主循环
function loop() {
  requestAnimationFrame(loop);

  var delta = clock.getDelta();
  if (mixer) mixer.update(delta);
  renderer.render(scene, camera);
  if(role) {
    if(role.position.z>2&&role.direction==0){
      role.direction = -1*Math.PI;
    }
    if(role.position.z<-2&&role.direction==-Math.PI){
      role.direction = 0;
    }
    role.rotation.y = role.direction;
    let moveZ = 0;
    switch (actionState) {
      case animations[0].name:
        if(role.direction==0) moveZ =0.015;
        else moveZ = -0.015;
        break;
      case animations[1].name:
        if(role.direction==0) moveZ =0.005;
        else moveZ = -0.005;
          break;
      case animations[2].name:
        if(role.direction==0) moveZ =0.0025;
        else moveZ = -0.0025;
          break;
      default:
        break;
    }
    console.log(moveZ)
    role.position.z += moveZ;
    camera.position.x -= moveZ;
  }

  // console.log(camera.position);
}

window.addEventListener(
  "resize",
  function () {
    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.camera.updateProjectionMatrix();
    renderer.setSize(document.body.clientWidth, document.body.clientHeight);
  },
  false
);

window.onload = init;
